import json
import os
import pickle
import re
import requests
from lxml import html

from src import utils
from src.verification_captcha import VerificationCaptcha


class User:
    login_url = 'https://spain.blscn.cn/CHN/Account/LogIn?ReturnUrl=%2FCHN%2Fblsappointment%2Fmanageappointment'
    cookies = None

    def __init__(self, user_name, password):
        self.user_name = user_name
        self.password = password

    def get_cookies(self):
        if self.cookies is None:
            if os.path.exists(self.user_name):
                with open(self.user_name, 'rb') as f:
                    self.cookies = pickle.load(f)
            else:
                self.login()
        return self.cookies

    def login(self):
        # start_time = time.time()
        htmlResponse = requests.get(self.login_url)
        if htmlResponse.status_code == 200:
            tree = html.fromstring(htmlResponse.content)
            # end_time = time.time()
            # print(f'运行时间: {end_time - start_time} 秒')
            # start_time = end_time
            cookies = htmlResponse.cookies
            __RequestVerificationToken = tree.xpath('//input[@name="__RequestVerificationToken"]')[0].get('value')
            CaptchaParam = tree.xpath('//input[@id="CaptchaParam"]')[0].get('value')
            ScriptData = tree.xpath('//input[@id="ScriptData"]')[0].get('value')
            CaptchaId = tree.xpath('//input[@id="CaptchaId"]')[0].get('value')
            ReturnUrl = tree.xpath('//input[@id="ReturnUrl"]')[0].get('value')
            # 正则表达式模式
            pattern = r"win\.iframeOpenUrl = '(.+?)'"
            # 使用re.search()函数进行匹配
            match = re.search(pattern, htmlResponse.content.decode('utf-8'))

            user_key, pass_key = get_login_data(tree)

            verifi = VerificationCaptcha(captcha_id=match.group(1), cookies=cookies, is_login=True)
            captcha_data = verifi.get_captcha_data()
            # end_time = time.time()
            # print(f'运行时间: {end_time - start_time} 秒')
            if captcha_data:
                login_data = {
                    'CaptchaId': CaptchaId,
                    'CaptchaData': captcha_data,
                    'ScriptData': ScriptData,
                    'CaptchaParam': CaptchaParam,
                    'ReturnUrl': ReturnUrl,
                    '__RequestVerificationToken': __RequestVerificationToken
                }

                login_cookies = login(login_data, cookies, user_key, pass_key, user_name=self.user_name,
                                      password=self.password)
                if login_cookies:
                    cookies.update(login_cookies)
                    with open(self.user_name, 'wb') as file:
                        pickle.dump(cookies, file)
                    self.cookies = cookies


def login(data, cookies, user_key, pass_key, user_name, password):
    loginData = {'UserId1': '', 'UserId2': '', 'UserId3': '', 'UserId4': '', 'UserId5': '', 'UserId6': '',
                 'UserId7': '', 'UserId8': '', 'UserId9': '', 'UserId10': '', 'Password1': '', 'Password2': '',
                 'Password3': '', 'Password4': '', 'Password5': '', 'Password6': '', 'Password7': '', 'Password8': '',
                 'Password9': '', 'Password10': '', 'ReturnUrl': data['ReturnUrl'], 'CaptchaId': data['CaptchaId'],
                 'CaptchaParam': data['CaptchaParam'], 'CaptchaData': data['CaptchaData'],
                 'ScriptData': data['ScriptData'], '__RequestVerificationToken': data['__RequestVerificationToken'],
                 'X-Requested-With': 'XMLHttpRequest', user_key: user_name, pass_key: password}

    headers = utils.get_headers()
    res = requests.post('https://spain.blscn.cn/CHN/account/loginsubmit', data=loginData, headers=headers,
                        cookies=cookies)
    json_obj = json.loads(res.content)
    if json_obj['success']:
        return res.cookies
    else:
        print(json_obj)


def get_login_data(tree):
    style_tags = tree.xpath('//style')
    user_key = ''
    pass_key = ''
    pattern = r'\.(\w+){display:block !important;}'
    matches = re.findall(pattern, style_tags[1].text)
    for rule in matches:
        divs = tree.xpath(
            '//div[contains(@class, "mb-3") and contains(@class, "position-relative") and contains('
            '@class, "' + rule + '")]//input')
        if len(divs) == 1:
            if 'UserId' in divs[0].get('name'):
                user_key = divs[0].get('name')
            else:
                pass_key = divs[0].get('name')

    return user_key, pass_key
